Máster en Data Science UAH

Tasador de viviendas de alquiler vacacional en Málaga

Notebook #3 - Estudio de la localización

Alumno: Héctor Mateos Oblanca
Tutor: Daniel Rodríguez Pérez

Intro

In [1]:
city = 'malaga'
month = '201909'
filename_in = 'src/data/' + city + '-' + month + '-listings-CLEAN.csv'
In [2]:
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, HTML
import featuretools as ft
import uuid
import s2sphere as s2
import random
 
import catboost as cb
from kmodes.kmodes import KModes
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score, cross_val_predict 
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error

import scipy.spatial as spatial
import plotly.express as px
import chart_studio.plotly as py
import plotly.graph_objs as go
from plotly.offline import iplot, init_notebook_mode

%run src/utils.py
In [3]:
coefs = {}
metrics = {}

def collect_results(columns, model, method, r2, mae, mse, skip_coef=True):
    # coefs
    if skip_coef != True:
        method_coefs = {}
        if hasattr(model, '__intercept'):
            method_coefs['__intercept'] = model.intercept_
        
        for i in range(len(columns.values)):
            method_coefs[columns.values[i]] = abs(model.coef_[i])
        coefs[method] = method_coefs
        df_coefs = pd.DataFrame(coefs)
        df_coefs = df_coefs.sort_values(by=method, ascending=False)
        display(df_coefs)
    
    # metrics
    metrics[method] = {
        'R2':r2.round(3),
        'MAE':mae.round(3),
        'MSE':mse.round(3)
    }
    
    display(pd.DataFrame(metrics))

def print_feature_importances(method, importances, df):
    feature_score = pd.DataFrame(list(zip(df.dtypes.index, importances)), columns=['Feature','Score'])
    feature_score = feature_score.sort_values(by='Score', 
                                              ascending=True, 
                                              inplace=False, 
                                              kind='quicksort', 
                                              na_position='last')
    
    fig = go.Figure(
        go.Bar(
            x=feature_score['Score'],
            y=feature_score['Feature'],
            orientation='h'
        )
    )
    
    fig.update_layout(
        title=method + " Feature Importance Ranking",
        height=25*len(feature_score)
    )
    
    fig.show()

Carga del dataset

In [4]:
df = pd.read_csv(filename_in)
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4466 entries, 0 to 4465
Data columns (total 61 columns):
host_response_time                      4466 non-null object
latitude                                4466 non-null float64
longitude                               4466 non-null float64
property_type                           4466 non-null object
room_type                               4466 non-null object
accommodates                            4466 non-null int64
bathrooms                               4466 non-null float64
bedrooms                                4466 non-null float64
price                                   4466 non-null float64
security_deposit                        4466 non-null float64
cleaning_fee                            4466 non-null float64
guests_included                         4466 non-null int64
extra_people                            4466 non-null float64
minimum_nights_avg_ntm                  4466 non-null float64
maximum_nights_avg_ntm                  4466 non-null float64
number_of_reviews                       4466 non-null int64
number_of_reviews_ltm                   4466 non-null int64
first_review                            4466 non-null object
last_review                             4466 non-null object
review_scores_rating                    4466 non-null float64
review_scores_accuracy                  4466 non-null float64
review_scores_cleanliness               4466 non-null float64
review_scores_checkin                   4466 non-null float64
review_scores_communication             4466 non-null float64
review_scores_location                  4466 non-null float64
review_scores_value                     4466 non-null float64
instant_bookable                        4466 non-null int64
cancellation_policy                     4466 non-null object
reviews_per_month                       4466 non-null float64
district                                0 non-null float64
neighbourhood                           4466 non-null object
has_wifi                                4466 non-null int64
has_essentials                          4466 non-null int64
has_kitchen                             4466 non-null int64
has_heating                             4466 non-null int64
has_washer                              4466 non-null int64
has_hangers                             4466 non-null int64
has_tv                                  4466 non-null int64
has_hair_dryer                          4466 non-null int64
has_iron                                4466 non-null int64
has_shampoo                             4466 non-null int64
has_laptop_friendly_workspace           4466 non-null int64
has_air_conditioning                    4466 non-null int64
has_hot_water                           4466 non-null int64
has_elevator                            4466 non-null int64
has_refrigerator                        4466 non-null int64
has_dishes_and_silverware               4466 non-null int64
has_microwave                           4466 non-null int64
has_bed_linens                          4466 non-null int64
has_no_stairs_or_steps_to_enter         4466 non-null int64
has_coffee_maker                        4466 non-null int64
has_cooking_basics                      4466 non-null int64
has_family/kid_friendly                 4466 non-null int64
has_long_term_stays_allowed             4466 non-null int64
has_first_aid_kit                       4466 non-null int64
has_oven                                4466 non-null int64
has_stove                               4466 non-null int64
has_license                             4466 non-null int64
activity_months                         4466 non-null float64
income_med_occupation                   4466 non-null float64
price_med_occupation_per_accommodate    4466 non-null float64
dtypes: float64(22), int64(32), object(7)
memory usage: 2.1+ MB

Descarte de características

In [5]:
useful_cols = [
    'accommodates',
    'bathrooms',
    'bedrooms',
    'cancellation_policy',
    'cleaning_fee',
    'extra_people',
    'guests_included',
    'has_air_conditioning',
    'has_bed_linens',
    'has_coffee_maker',
    'has_cooking_basics',
    'has_dishes_and_silverware',
    'has_elevator',
    'has_essentials',
    'has_family/kid_friendly',
    'has_first_aid_kit',
    'has_hair_dryer',
    'has_hangers',
    'has_heating',
    'has_hot_water',
    'has_iron',
    'has_kitchen',
    'has_laptop_friendly_workspace',
    'has_license',
    'has_long_term_stays_allowed',
    'has_microwave',
    'has_no_stairs_or_steps_to_enter',
    'has_oven',
    'has_refrigerator',
    'has_shampoo',
    'has_stove',
    'has_tv',
    'has_washer',
    'has_wifi',
    'instant_bookable',
    'latitude',
    'longitude',
    'maximum_nights_avg_ntm',
    'minimum_nights_avg_ntm',
    'neighbourhood',
    'price',
    'property_type',
    'room_type',
    'security_deposit'
]

useless_cols = [
    'district',
    'income_med_occupation',
    'activity_months',
    'first_review',
    'last_review',
    'number_of_reviews',
    'number_of_reviews_ltm',
    'review_scores_rating',
    'review_scores_accuracy',
    'review_scores_cleanliness',
    'review_scores_checkin',
    'review_scores_communication',
    'review_scores_location',
    'review_scores_value',
    'reviews_per_month'
]

highly_corr_cols = [
    'has_refrigerator', 
    'host_verified_by_selfie'
]

df.drop([*useless_cols, *highly_corr_cols], axis=1, errors='ignore', inplace=True)
df.shape
Out[5]:
(4466, 45)

Nuevas características de localización calculadas

Distancia a puntos de interés

Se calcula para cada propiedad la distancia en kilómetros a diferentes puntos de interés turístico de la ciudad.

In [6]:
pois = [    
    {'name':'alcazaba', 'coord':(36.721, -4.416)},
    {'name':'museo-picasso', 'coord':(36.721771, -4.41847)},
    {'name':'catedral', 'coord':(36.720042, -4.42012)},
    {'name':'gibralfaro', 'coord':(36.72333333, -4.41166667)},
    {'name':'aeropuerto', 'coord':(36.6777495, -4.4901616)},
    {'name':'puerto', 'coord':(36.71666667, -4.41666667)},
    {'name':'calle-larios', 'coord':(36.719827777778, -4.4216222222222)},
    {'name':'estadio-la-rosaleda', 'coord':(36.734092, -4.426422)},
    {'name':'plaza-toros-malagueta', 'coord':(36.720333, -4.410806)},
    {'name':'playa-malagueta', 'coord':(36.71635, -4.41078)}
]
In [7]:
for poi in pois:
    df['dist_' + poi['name']] = df.apply(
        lambda r: get_haversine_distance(
            r['latitude'], 
            r['longitude'], 
            poi['coord']), 
        axis=1)

Clustering de barrios

La característica neighbourhood tiene una cardinalidad muy alta que puede conducir a sobreajuste puesto que en algunos barrios hay pocos datos. Se propone, utilizando clusterización, una característica de cardinalidad intermedia entre barrios y distritos que agrupe barrios similares y que resulte más representativa para el estudio.

In [8]:
km = KModes(n_clusters=15, init='Huang', n_init=10, random_state=42)
df['nb_cluster'] = km.fit_predict(df[['price_med_occupation_per_accommodate', 'neighbourhood']])
clusters = df['nb_cluster'].copy()
df['nb_cluster'] = df['nb_cluster'].apply(lambda x: 'nb_' + str(x))
df.drop(['price_med_occupation_per_accommodate'], axis=1, inplace=True) # solo era para calcular clusters
In [9]:
cluster_map = pd.DataFrame(list(zip(df['neighbourhood'], clusters)), columns=['nb', 'cluster'])
cluster_map.drop_duplicates(inplace=True)

with open('src/geo/' + city + '.neighbourhoods.geojson') as f:
    city_nb = fix_geojson(json.load(f))
    
fig = go.Figure(go.Choroplethmapbox(
    geojson=city_nb,
    locations=cluster_map['nb'], 
    z=cluster_map['cluster'],                   
    colorscale=px.colors.qualitative.Vivid,                                
    marker_opacity=0.5, 
    marker_line_width=0.2
))

fig.update_layout(
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0},
    title='clusters',
    showlegend=False
)

fig.show()

Celdas S2

In [10]:
def get_s2(lat, lng):
    py_cellid = s2.CellId.from_lat_lng(
        s2.LatLng.from_degrees(lat, lng)
    )
    py_cellid = py_cellid.parent(12)
    return 's2_' + str(py_cellid.id())

df['s2'] = df.apply(lambda r: get_s2(r['latitude'], r['longitude']), axis=1)
In [11]:
df_s2 = df[['s2', 'latitude', 'longitude']]
s2_cells = sorted(df_s2['s2'].unique())
random.shuffle(s2_cells)
df_s2['idx'] = df_s2['s2'].apply(lambda x: s2_cells.index(x))
In [12]:
fig314 = go.Figure()

fig314.add_trace(go.Scattermapbox(
    lon=df_s2['longitude'],
    lat=df_s2['latitude'],
    mode='markers',
    marker_color=df_s2['idx'],
    text=df_s2['idx'],
    marker=dict(
        size=5,
        opacity=0.4,
        colorscale='spectral'
    )
))

fig314.update_layout(
    showlegend=False,
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig314.show()

Regiones Voronoi

In [13]:
poi_coords = list(map(lambda x: x['coord'], pois))
vor = spatial.Voronoi(poi_coords)

def get_voronoi_index(row):
    new_point = [row['latitude'], row['longitude']]
    point_index = np.argmin(np.sum((vor.points - new_point)**2, axis=1))
    return 'v_' + str(point_index)

df['voronoi'] = df.apply(lambda r: get_voronoi_index(r), axis=1)
spatial.voronoi_plot_2d(vor)
Out[13]:
In [14]:
df_voronoi = df[['voronoi', 'latitude', 'longitude']]
voronoi_cells = sorted(df_voronoi['voronoi'].unique())
df_voronoi['idx'] = df_voronoi['voronoi'].apply(lambda x: voronoi_cells.index(x))
In [15]:
fig315 = go.Figure()

fig315.add_trace(go.Scattermapbox(
    lon=df_voronoi['longitude'],
    lat=df_voronoi['latitude'],
    mode='markers',
    marker_color=df_voronoi['idx'],
    text=df_voronoi['idx'],
    marker=dict(
        size=5,
        opacity=0.4,
        colorscale='spectral'
    )
))

fig315.add_trace(
    go.Scattermapbox(
        lat=list(map(lambda x: x['coord'][0], pois)),
        lon=list(map(lambda x: x['coord'][1], pois)),
        text=list(map(lambda x: x['name'], pois)),
        mode='markers',
        marker=dict(
            size=8,
            opacity=0.9,
            color='black'
        )
    )
)

fig315.update_layout(
    showlegend=False,
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':df['latitude'].mean(), 'lon':df['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig315.show()

Conversión de características categóricas en dummies

In [16]:
print(df.shape)
dfd = pd.get_dummies(df)
print(dfd.shape)

target = 'price'
features = list(dfd.columns)
features.remove(target)
(4466, 57)
(4466, 141)

Partición en conjuntos de entrenamiento y test

In [17]:
x_train, x_test, y_train, y_test = train_test_split(
    dfd[features], 
    dfd[target],
    test_size=0.3,
    random_state=42
)

x_train = x_train.astype(float) # prevent conversion warnings

Modelo base: Random Forest

In [18]:
def eval_model(method, cols, df):
    model = RandomForestRegressor(random_state=42, n_estimators=200)    
    regressor = Pipeline([('model', model)])
    regressor.fit(x_train[cols], y_train)
    y_pred = regressor.predict(x_test[cols])
    r2 = r2_score(y_test, y_pred)
    mae = mean_absolute_error(y_test, y_pred)
    mse = mean_squared_error(y_test, y_pred)
    
    collect_results(cols, model, method, r2, mae, mse, skip_coef=True)
    importances = regressor.named_steps['model'].feature_importances_
    print_feature_importances(method, importances, df[cols])
    return y_pred

Estudio de la localización

In [19]:
neighbourhood_cols = [col for col in dfd if col.startswith('neighbourhood')]
dist_cols = [col for col in dfd if col.startswith('dist_')]
coord_cols = ['latitude', 'longitude']
nb_cluster_cols = [col for col in dfd if col.startswith('nb_cluster_')]
s2_cols = [col for col in dfd if col.startswith('s2_')]
voronoi_cols = [col for col in dfd if col.startswith('voronoi')]

Modelo sin variable geográfica

Este modelo registraría toda la variabilidad de precio que es debida a las propiedades de las viviendas sin considerar caractarísticas geográficas de ningún tipo.

In [20]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('NO-GEO', cols, dfd)
NO-GEO
MAE 16.580
MSE 750.769
R2 0.583

Residuos

Se busca si existen zonas con un error positivo o negativo.

  • Lo que se puede asociar con puntos de interés: positivo
  • Zonas que los visitantes prefieren evitar: negativo
In [21]:
x_test['resid'] = y_test - y_pred
plt.hist(x_test['resid'], bins=50)
plt.show()

Residuos outliers

In [22]:
x_test2 = x_test.copy()
x_test2.reset_index(inplace=True)
outliers_idx = get_outliers_iqr(x_test2['resid'])[0]
remove_outliers(x_test2, outliers_idx, 'resid')
outliers between following bounds: -40.89990000000007 35.12750000000004
124 outliers to be removed with values: [-89.36999999999998, -81.3419999999999, -70.62750000000004, -70.01099999999991, -69.64949999999997, -67.82849999999996, -67.00949999999999, -66.79500000000002, -66.17250000000004, -62.10449999999997, -57.15900000000002, -54.86850000000011, -54.00449999999998, -52.97849999999997, -52.86149999999998, -51.759, -51.21449999999999, -49.549499999999966, -49.21649999999999, -48.84749999999997, -48.22049999999993, -47.86650000000003, -46.92000000000007, -46.79400000000001, -46.601999999999975, -45.91349999999998, -45.85500000000003, -45.74700000000004, -45.52200000000001, -45.40050000000002, -45.12900000000001, -44.68050000000002, -44.53200000000004, -42.5805, -42.39000000000007, -41.483250000000005, -41.116499999999974, -41.03999999999998, -40.99199999999998, 35.28899999999996, 35.40150000000003, 35.594999999999985, 35.608499999999985, 37.39949999999995, 37.439999999999955, 37.655999999999985, 38.241000000000156, 38.772749999999974, 38.84400000000001, 39.250875, 39.72974999999996, 40.49774999999998, 40.509749999999976, 42.36749999999996, 43.393499999999946, 43.44300000000007, 43.87950000000001, 44.37449999999994, 45.152999999999984, 45.18412499999993, 45.64349999999997, 46.15424999999999, 46.21274999999997, 46.84949999999997, 47.817000000000036, 48.334499999999935, 48.563999999999936, 49.06125, 50.79600000000002, 50.89500000000001, 53.08649999999996, 54.710999999999984, 55.28699999999998, 56.164499999999975, 57.97800000000001, 58.65449999999994, 58.79475000000001, 60.69000000000001, 61.03349999999996, 61.72087500000002, 63.22874999999996, 64.21500000000002, 65.007, 66.23100000000001, 66.35099999999994, 67.54564285714285, 67.60162500000001, 69.72750000000002, 70.01549999999996, 70.744125, 71.42250000000008, 72.75875357142854, 74.91149999999993, 75.14999999999995, 77.1210000000001, 79.09537499999999, 79.12349999999986, 82.791, 85.61250000000007, 85.96594999999999, 88.83000000000004, 91.12049999999998, 104.283, 107.6805, 108.99600000000004, 109.98449999999993, 111.95999999999998, 112.023, 114.07050000000001, 118.85850000000005, 119.43150000000001, 119.67337499999998, 124.07850000000008, 125.77049999999997, 126.82725, 130.209, 131.52149999999997, 139.72649999999996, 142.44937500000003, 147.58199999999994, 165.8474999999999, 187.27650000000006, 201.66299999999995, 215.52300000000005]
In [23]:
plt.hist(x_test2['resid'], bins=30)
plt.show()
In [24]:
fig1 = go.Figure(
    go.Scattermapbox(
        lon=x_test2['longitude'],
        lat=x_test2['latitude'],
        mode='markers',
        marker_color=x_test2['resid'],
        text=x_test2['resid'],
        marker=dict(
            opacity=0.8,
            colorscale=[
                [0.0, "rgb(165,0,38)"],
                [0.11, "rgb(215,48,39)"],
                [0.22, "rgb(244,109,67)"],
                [0.33, "rgb(253,174,97)"],
                [0.44, "rgb(254,224,144)"],
                [0.55, "rgb(224,243,248)"],
                [0.66, "rgb(171,217,233)"],
                [0.77, "rgb(116,173,209)"],
                [0.88, "rgb(69,117,180)"],
                [1.0, "rgb(49,54,149)"]
            ]
        )
    )
)

fig1.update_layout(
    mapbox_style='carto-positron',
    mapbox_zoom=11, 
    mapbox_center={'lat':x_test2['latitude'].mean(), 'lon':x_test2['longitude'].mean()},
    margin={"r":0,"t":0,"l":0,"b":0}
)

fig1.show()

Coordenadas

In [25]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('COORD', cols, dfd)
NO-GEO COORD
R2 0.583 0.589
MAE 16.580 16.344
MSE 750.769 741.044

Barrios

In [26]:
cols = features.copy()
for c in [*dist_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('NB', cols, dfd)
NO-GEO COORD NB
R2 0.583 0.589 0.583
MAE 16.580 16.344 16.601
MSE 750.769 741.044 751.539

Cluster de barrios

In [27]:
cols = features.copy()
for c in [*neighbourhood_cols, *dist_cols, *coord_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('CLUSTER-NB', cols, dfd)
NO-GEO COORD NB CLUSTER-NB
R2 0.583 0.589 0.583 0.583
MAE 16.580 16.344 16.601 16.548
MSE 750.769 741.044 751.539 751.268

Distancias a puntos de interés

In [28]:
cols = features.copy()
for c in [*neighbourhood_cols, *coord_cols, *nb_cluster_cols, *s2_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('DIST', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST
R2 0.583 0.589 0.583 0.583 0.588
MAE 16.580 16.344 16.601 16.548 16.484
MSE 750.769 741.044 751.539 751.268 741.574

Voronoi

In [29]:
cols = features.copy()
for c in [*neighbourhood_cols, *nb_cluster_cols, *coord_cols, *dist_cols, *s2_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('VORONOI', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI
R2 0.583 0.589 0.583 0.583 0.588 0.580
MAE 16.580 16.344 16.601 16.548 16.484 16.614
MSE 750.769 741.044 751.539 751.268 741.574 756.728

S2

In [30]:
cols = features.copy()
for c in [*neighbourhood_cols, *nb_cluster_cols, *coord_cols, *dist_cols, *voronoi_cols]:
    if c in cols:
        cols.remove(c)
    
y_pred = eval_model('S2', cols, dfd)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI S2
R2 0.583 0.589 0.583 0.583 0.588 0.580 0.581
MAE 16.580 16.344 16.601 16.548 16.484 16.614 16.508
MSE 750.769 741.044 751.539 751.268 741.574 756.728 754.256

Automated feature engineering

In [31]:
auto_df = df.copy()
auto_df['auto_id'] = auto_df['price'].apply(lambda x: uuid.uuid1().int)
prices = auto_df['price']
auto_df.drop(['price'], axis=1, inplace=True, errors='ignore')
In [32]:
es = ft.EntitySet(id='airbnb')
es = es.entity_from_dataframe(
    entity_id='main',
    dataframe=auto_df,
    index='auto_id'
)
In [33]:
# available_transform_primitives = ft.primitives.list_primitives()
# print(available_transform_primitives[available_transform_primitives['type'] == 'transform'])

features_df, feature_names = ft.dfs(
    entityset=es,
    target_entity='main',
    trans_primitives=['subtract_numeric'],
    max_depth=2
)

# print(features_df.columns)
In [34]:
auto_df = features_df.copy()
auto_df.reset_index()
auto_df.drop(['auto_id'], axis=1, inplace=True, errors='ignore')

auto_df = pd.get_dummies(auto_df)
print(auto_df.shape)

auto_features = list(auto_df.columns)

x_train, x_test, y_train, y_test = train_test_split(
    auto_df, 
    prices,
    random_state=42
)

x_train = x_train.astype(float) # prevent conversion warnings
(4466, 1268)
In [35]:
y_pred = eval_model('AUTO-FT', auto_features, auto_df)
NO-GEO COORD NB CLUSTER-NB DIST VORONOI S2 AUTO-FT
R2 0.583 0.589 0.583 0.583 0.588 0.580 0.581 0.557
MAE 16.580 16.344 16.601 16.548 16.484 16.614 16.508 17.038
MSE 750.769 741.044 751.539 751.268 741.574 756.728 754.256 825.872